module.exports = function ($scope, $state, $resource, $modal, toaster, $stateParams) {

	$scope.customSettings = {
		control: 'brightness',
		theme: 'bootstrap',
		position: 'top left',
	};

	// $scope.times = $stateParams.params ? eval('(' + $stateParams.params + ')') : {};
	$scope.times = $stateParams.params? angular.fromJson(decodeURIComponent($stateParams.params)): {};
	// $scope.times = $stateParams.params? $scope.$eval($stateParams.params): {};
	$scope.mapStr = [];
	$scope.unavailable = [];
	$scope.loadlist = function () {
		$scope.selectMap = {};
		$scope.mapStr = [];
		$scope.unavailable = [];
		var para = {
			'shows_code': $scope.times.code
		}
		$resource('/api/ac/fc/filmShowsService/getFilmShowsLayoutList', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				$('#selected-seats').html('');
				$('#seat-map').html('');
				$('#legend').html('');
				$scope.priceList = res.data.filmShowsColourPriceList;
				for (var index = 0; index < $scope.priceList.length; index++) {
					var element = $scope.priceList[index];
					element.style = {
						'background-color': element.colour_value,
						'color': 'black'
					}
				}
				$scope.roomList = res.data.filmShowsLayoutList;
				//拼座位图
				for (var index = 0; index < $scope.roomList.length; index++) {
					var element = $scope.roomList[index];
					if (element.column_posi - 1 == 0) {
						$scope.mapStr[element.line_posi - 1] = '';
					}
					$scope.mapStr[element.line_posi - 1] += 'a';
					if (element.state == '0') {
						$scope.unavailable.push(element.line_posi + '_' + element.column_posi)
					}
				}
				//生成座位
				$scope.makeData();
				for (var index = 0; index < $scope.roomList.length; index++) {
					var element = $scope.roomList[index];
					//给座位加颜色
					if (element.colour_value) {
						$('#' + element.line_posi + '_' + element.column_posi).css('background-color', element.colour_value)
					}
					//预留的座位画X
					if (element.sale_state == '2' && element.state != '0') {
						$('#' + element.line_posi + '_' + element.column_posi).html('<span class="glyphicon glyphicon-remove"></span>')
					}
				}
			} else {
				toaster.error({ title: '', body: res.errmsg });
			}
		});
	}
	$scope.loadlist();

	$scope.selectMap = {};//选中数据
	$scope.color;//颜色
	$scope.cost_price;//成本价
	$scope.guide_price;//居游价
	$scope.market_price;//市场价
	//价格颜色
	$('.set-price-color').bind('click', function (params) {
		if (!$scope.color || $scope.cost_price === undefined || $scope.guide_price === undefined || $scope.market_price === undefined) {
			alert('请输入价格和颜色');
			return false;
		}
		var posi_list = [];
		for (var key in $scope.selectMap) {
			posi_list.push({
				line_posi: key.split('_')[0],
				column_posi: key.split('_')[1]
			})
		}
		if (posi_list.length < 1) {
			alert('请选择座位');
			return false;
		}
		var para = {
			'shows_code': $scope.times.code,
			'posi_list': posi_list,
			'colour_value': $scope.color,
			'cost_price': $scope.cost_price * 100,
			'guide_price': $scope.guide_price * 100,
			'market_price': $scope.market_price * 100,
		}
		$resource('/api/ac/fc/filmShowsService/updateShowsLayoutPrice', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				// $scope.update();
				toaster.success({ title: '', body: '更新成功' });
				// window.history.back();
				$scope.loadlist();
			} else {
				toaster.error({ title: '', body: res.errmsg });
			}
		});
	})

	//预留座位
	$('.set-yuliu-seat').bind('click', function (params) {
		var posi_list = [];
		for (var key in $scope.selectMap) {
			posi_list.push({
				line_posi: key.split('_')[0],
				column_posi: key.split('_')[1]
			})
		}
		if (posi_list.length < 1) {
			toaster.warning({ title: '', body: '请选择座位' });
			return false;
		}
		var para = {
			'shows_code': $scope.times.code,
			'posi_list': posi_list
		}
		$resource('/api/ac/fc/filmShowsService/updateShowsLayoutNoAllowSale', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				// $scope.update();
				toaster.success({ title: '', body: '更新成功' });
				// window.history.back();
				$scope.loadlist();
			} else {
				toaster.error({ title: '', body: res.errmsg });
			}
		});
	})

	//取消预留座位
	$('.canel-yuliu-seat').bind('click', function () {
		var posi_list = [];
		for (var key in $scope.selectMap) {
			posi_list.push({
				line_posi: key.split('_')[0],
				column_posi: key.split('_')[1]
			})
		}
		if (posi_list.length < 1) {
			toaster.warning({ title: '', body: '请选择座位' });
			return false;
		}
		var para = {
			'shows_code': $scope.times.code,
			'posi_list': posi_list
		}
		$resource('/api/ac/fc/filmShowsService/updateShowsLayoutAllowSale', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				// $scope.update();
				toaster.success({ title: '', body: '更新成功' });
				// window.history.back();
				$scope.loadlist();
			} else {
				toaster.error({ title: '', body: res.errmsg });
			}
		});
	})

	$('.seat-look').bind('click', function () {
        var modalInstance = $modal.open({
            template: require('../views/previewTimesLayout.html'),
            controller: 'previewTimesLayout',
            size: 'lg',
            resolve: {
                times: function () {
                    return $scope.times;
                },
            }
        });
        //关闭模态框刷新页面
        modalInstance.result.then(function () {
            $scope.loadlist();
        });
    })

	$scope.setPricecolor = function (price) {
		if(!confirm('确认选中区域设置为和本项相同的颜色和价格')){
			return false;
		}
		var posi_list = [];
		for (var key in $scope.selectMap) {
			posi_list.push({
				line_posi: key.split('_')[0],
				column_posi: key.split('_')[1]
			})
		}
		if (posi_list.length < 1) {
			alert('请选择座位');
			return false;
		}
		var para = {
			'shows_code': $scope.times.code,
			'posi_list': posi_list,
			'colour_value': price.colour_value
		}
		$resource('/api/ac/fc/filmShowsService/updateShowsLayoutPriceByColour', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				// $scope.update();
				toaster.success({ title: '', body: '更新成功' });
				// window.history.back();
				$scope.loadlist();
			} else {
				toaster.error({ title: '', body: res.errmsg });
			}
		});
	}


	$scope.makeData = function () {
		(function (e) {
			$('#seat-map').css('max-height', document.body.clientWidth - 620);
			e.fn.seatCharts = function (t) {
				if (this.data("seatCharts")) {
					this.data("seatCharts", {})
					// return this.data("seatCharts")
				}
				var n = this,
					r = {},
					i = [],
					s, o = {
						animate: false,
						naming: {
							top: true, left: true, getId: function (e, t, n) { return t + "_" + n }, getLabel: function (e, t, n) { return n }
						},
						legend: {
							node: null, items: []
						},
						click: function () {
							if (this.status() == "available") { return "selected" } else if (this.status() == "selected") { return "available" } else { return this.style() }
						},
						focus: function () {
							if (this.status() == "available") { return "focused" } else { return this.style() }
						},
						blur: function () {
							return this.status()
						},
						seats: {}
					},
					u = function (t, n) {
						return function (i) {
							var s = this;
							s.settings = e.extend({
								status: "available", style: "available", data: n.seats[i.character] || {}
							}, i);
							s.settings.$node = e("<div></div>");
							s.settings.$node.attr({ id: s.settings.id, role: "checkbox", "aria-checked": false, focusable: true, tabIndex: -1 })
								.text(s.settings.label)
								.addClass(
								["seatCharts-seat", "seatCharts-cell", "available"]
									.concat(s.settings.classes, typeof n.seats[s.settings.character] == "undefined" ? [] : n.seats[s.settings.character].classes)
									.join(" ")
								);
							s.data = function () { return s.settings.data };
							s.char = function () { return s.settings.character };
							s.node = function () { return s.settings.$node };
							s.style = function () {
								return arguments.length == 1 ? function (e) {
									var t = s.settings.style;
									if (e == t) { return t }
									s.settings.status = e != "focused" ? e : s.settings.status;
									s.settings.$node.attr("aria-checked", e == "selected");
									n.animate ? s.settings.$node.switchClass(t, e, 200) : s.settings.$node.removeClass(t).addClass(e);
									return s.settings.style = e
								}(arguments[0]) : s.settings.style
							};
							s.status = function () {
								return s.settings.status = arguments.length == 1 ? s.style(arguments[0]) : s.settings.status
							};
							(function (i, o, u) {
								e.each(["click", "focus", "blur"], function (e, a) {
									s[a] = function () {
										if (a == "focus") {
											if (t.attr("aria-activedescendant") !== undefined) {
												r[t.attr("aria-activedescendant")].blur()
											}
											t.attr("aria-activedescendant", u.settings.id);
											u.node().focus()
										} return s.style(typeof i[o][a] === "function" ? i[o][a].apply(u) : n[a].apply(u))
									}
								})
							})(n.seats, s.settings.character, s);
							s.node()
								.on("click", s.click)
								.on("mouseenter", s.focus)
								.on("mouseleave", s.blur)
								.on("keydown", function (e, n) {
									return function (i) {
										var s;
										switch (i.which) {
											case 32:
												i.preventDefault();
												e.click();
												break;
											case 40:
											case 38:
												i.preventDefault();
												s = function o(e, t, r) {
													var u;
													if (!e.index(r) && i.which == 38) {
														u = e.last()
													} else if (e.index(r) == e.length - 1 && i.which == 40) {
														u = e.first()
													} else {
														u = e.eq(e.index(r) + (i.which == 38 ? -1 : +1))
													}
													s = u.find(".seatCharts-seat,.seatCharts-space").eq(t.index(n));
													return s.hasClass("seatCharts-space") ? o(e, t, u) : s
												}(
													n.parents(".seatCharts-container").find(".seatCharts-row:not(.seatCharts-header)"),
													n.parents(".seatCharts-row:first").find(".seatCharts-seat,.seatCharts-space"),
													n.parents(".seatCharts-row:not(.seatCharts-header)")
													);
												if (!s.length) { return }
												e.blur();
												r[s.attr("id")].focus();
												s.focus();
												t.attr("aria-activedescendant", s.attr("id"));
												break;
											case 37:
											case 39:
												i.preventDefault();
												s = function (e) {
													if (!e.index(n) && i.which == 37) {
														return e.last()
													} else if (e.index(n) == e.length - 1 && i.which == 39) {
														return e.first()
													} else {
														return e.eq(e.index(n) + (i.which == 37 ? -1 : +1))
													}
												}(
													n.parents(".seatCharts-container:first").find(".seatCharts-seat:not(.seatCharts-space)")
													);
												if (!s.length) { return }
												e.blur();
												r[s.attr("id")].focus();
												s.focus();
												t.attr("aria-activedescendant", s.attr("id"));
												break;
											default:
												break
										}
									}
								}(s, s.node()))
						}
					}(n, o);
				n.addClass("seatCharts-container");
				e.extend(true, o, t);
				o.naming.rows = o.naming.rows || function (e) { var t = []; for (var n = 1; n <= e; n++) { t.push(n) } return t }(o.map.length);
				o.naming.columns = o.naming.columns || function (e) { var t = []; for (var n = 1; n <= e; n++) { t.push(n) } return t }(o.map[0].split("").length);
				if (o.naming.top) {
					var a = e("<div></div>").addClass("seatCharts-row seatCharts-header");
					if (o.naming.left) {
						a.append(e("<div></div>").addClass("seatCharts-cell"))
					}
					e.each(o.naming.columns, function (t, n) {
						a.append(e("<div></div>").addClass("seatCharts-cell").text(n))
					})
				}
				n.append(a);
				e.each(o.map, function (t, s) {
					var a = e("<div></div>").addClass("seatCharts-row");
					if (o.naming.left) {
						a.append(e("<div></div>").addClass("seatCharts-cell seatCharts-space").text(o.naming.rows[t]))
					}
					e.each(s.match(/[a-z_]{1}(\[[0-9a-z_]{0,}(,[0-9a-z_ ]+)?\])?/gi), function (n, s) {
						var f = s.match(/([a-z_]{1})(\[([0-9a-z_ ,]+)\])?/i),
							l = f[1],
							c = typeof f[3] !== "undefined" ? f[3].split(",") : [],
							h = c.length ? c[0] : null,
							p = c.length === 2 ? c[1] : null;
						a.append(l != "_" ? function (e) {
							o.seats[l] = l in o.seats ? o.seats[l] : {};
							var s = h ? h : e.getId(l, e.rows[t], e.columns[n]);
							r[s] = new u({ id: s, label: p ? p : e.getLabel(l, e.rows[t], e.columns[n]), row: t, column: n, character: l });
							i.push(s);
							return r[s].node()
						}(o.naming) : e("<div></div>").addClass("seatCharts-cell seatCharts-space"))
					});
					n.append(a)
				});
				o.legend.items.length ? function (t) {
					var r = (t.node || e("<div></div").insertAfter(n)).addClass("seatCharts-legend");
					var i = e("<ul></ul>").addClass("seatCharts-legendList").appendTo(r);
					e.each(t.items, function (t, n) {
						i.append(
							e("<li></li>")
								.addClass("seatCharts-legendItem")
								.append(
								e("<div></div>")
									.addClass(["seatCharts-seat", "seatCharts-cell", n[1]].concat(o.classes, typeof o.seats[n[0]] == "undefined" ? [] : o.seats[n[0]].classes).join(" "))
								)
								.append(e("<span></span>").addClass("seatCharts-legendDescription").text(n[2]))
						)
					});
					return r
				}(o.legend) : null;
				n.attr({ tabIndex: 0 });
				n.focus(function () {
					if (n.attr("aria-activedescendant")) {
						r[n.attr("aria-activedescendant")].blur()
					}
					n.find(".seatCharts-seat:not(.seatCharts-space):first").focus();
					r[i[0]].focus()
				});
				n.data("seatCharts", {
					seats: r,
					seatIds: i,
					status: function () {
						var t = this;
						return arguments.length == 1 ? t.seats[arguments[0]].status() : function (n, r) {
							return typeof n == "string" ? t.seats[n].status(r) : function () {
								e.each(n, function (e, n) { t.seats[n].status(r) })
							}()
						}(arguments[0], arguments[1])
					}, each: function (e) {
						var t = this; for (var n in t.seats) { if (false === e.call(t.seats[n], n)) { return n } } return true
					},
					node: function () {
						var t = this; return e("#" + t.seatIds.join(",#"))
					},
					find: function (e) {
						var t = this;
						var n = t.set();
						return e.length == 1 ? function (e) {
							t.each(function () { if (this.char() == e) { n.push(this.settings.id, this) } }); return n
						}(e) : function () {
							return e.indexOf(".") > -1 ? function () {
								var r = e.split("."); t.each(function (e) { if (this.char() == r[0] && this.status() == r[1]) { n.push(this.settings.id, this) } }); return n
							}() : function () {
								t.each(function () {
									if (this.status() == e) {
										n.push(this.settings.id, this)
									}
								});
								return n
							}()
						}()
					},
					set: function f() {
						var t = this; return {
							seats: [],
							seatIds: [],
							length: 0,
							status: function () {
								var t = arguments,
									n = this;
								return this.length == 1 && t.length == 0 ? this.seats[0].status() : function () {
									e.each(n.seats, function () {
										this.status.apply(this, t)
									})
								}()
							},
							node: function () {
								return t.node.call(this)
							},
							each: function () {
								return t.each.call(this, arguments[0])
							},
							get: function () {
								return t.get.call(this, arguments[0])
							},
							find: function () {
								return t.find.call(this, arguments[0])
							},
							set: function () {
								return f.call(t)
							},
							push: function (e, t) {
								this.seats.push(t); this.seatIds.push(e); ++this.length
							}
						}
					},
					get: function (t) {
						var n = this;
						return typeof t == "string" ? n.seats[t] : function () {
							var r = n.set();
							e.each(t, function (e, t) {
								if (typeof n.seats[t] === "object") { r.push(t, n.seats[t]) }
							});
							return r
						}()
					}
				});
				return n.data("seatCharts")
			}
		})(jQuery)
		var sc = $('#seat-map').seatCharts({
			map: $scope.mapStr,
			// [  //座位图
			//     'aaaaaaaaaa',
			//     'aaaaaaaaaa',
			//     '__________',
			//     'aaaaaaaa__',
			//     'aaaaaaaaaa',
			//     'aaaaaaaaaa',
			//     'aaaaaaaaaa',
			//     'aaaaaaaaaa',
			//     'aaaaaaaaaa',
			//     'aa__aa__aa'
			// ],
			naming: {
				top: false,
				getLabel: function (character, row, column) {
					return column;
				}
			},
			legend: { //定义图例
				node: $('#legend'),
				items: [
					['a', 'available', '可选座'],
					['a', 'unavailable', '不可选']
				]
			},
			click: function () { //点击事件
				if (this.status() == 'available') { //可选座
					$scope.selectMap[(this.settings.row + 1) + '_' + (this.settings.column + 1)] = 'available';
					//记录选中前颜色
					this.settings.color_value = $('#' + (this.settings.row + 1) + '_' + (this.settings.column + 1)).css('background-color')
					//自定义颜色清空
					$('#' + (this.settings.row + 1) + '_' + (this.settings.column + 1)).css('background-color', '')
					return 'selected';
				} else if (this.status() == 'selected') { //已选中
					var status = $scope.selectMap[(this.settings.row + 1) + '_' + (this.settings.column + 1)];
					delete $scope.selectMap[(this.settings.row + 1) + '_' + (this.settings.column + 1)];
					if (status == 'available') {//可以选择的座位才有自定义颜色
						//还原选中前颜色
						$('#' + (this.settings.row + 1) + '_' + (this.settings.column + 1)).css('background-color', this.settings.color_value)
					}
					return status;
				} else if (this.status() == 'unavailable') { //已售出
					return 'unavailable';
					// $scope.selectMap[(this.settings.row + 1) + '_' + (this.settings.column + 1)] = 'unavailable';
					// return 'selected';
				} else {
					return this.style();
				}
			}
		});
		//已售出的座位
		// sc.get(['1_2', '4_4', '4_5', '6_6', '6_7', '8_5', '8_6', '8_7', '8_8', '10_1', '10_2']).status('unavailable');
		sc.get($scope.unavailable).status('unavailable');
	}

	$scope.timesSeatSelect = function () {
		var selList = [];
		var fileNodes = document.getElementsByTagName("div");
		for (var i = 0; i < fileNodes.length; i++) {
			if (fileNodes[i].className.indexOf("seatCharts-cell") != -1) {
				$(fileNodes[i]).removeClass('seled');
				selList.push(fileNodes[i]);
			}
		}
		var isSelect = true;
		var evt = window.event || arguments[0];
		var startX = (evt.x || evt.clientX);
		var startY = (evt.y || evt.clientY);
		var selDiv = document.createElement("div");
		selDiv.style.cssText = "position:absolute;width:0px;height:0px;font-size:0px;margin:0px;padding:0px;border:1px dashed #0099FF;background-color:#C3D5ED;z-index:1000;filter:alpha(opacity:60);opacity:0.6;display:none;";
		selDiv.id = "selectDiv";
		document.body.appendChild(selDiv);
		selDiv.style.left = startX + "px";
		selDiv.style.top = startY + "px";
		var _x = null;
		var _y = null;
		clearEventBubble(evt);
		document.onmousemove = function () {
			evt = window.event || arguments[0];
			if (isSelect) {
				if (selDiv.style.display == "none") {
					selDiv.style.display = "";
				}
				_x = (evt.x || evt.clientX);
				_y = (evt.y || evt.clientY);
				selDiv.style.left = Math.min(_x, startX) + "px";
				selDiv.style.top = Math.min(_y, startY) + "px";
				selDiv.style.width = Math.abs(_x - startX) + "px";
				selDiv.style.height = Math.abs(_y - startY) + "px";

				// ---------------- 关键算法 ---------------------  
				var _l = selDiv.offsetLeft,
					_t = selDiv.offsetTop;
				var _w = selDiv.offsetWidth,
					_h = selDiv.offsetHeight;
				for (var i = 0; i < selList.length; i++) {
					var sl = selList[i].offsetWidth + $(selList[i]).offset().left;
					var st = selList[i].offsetHeight + $(selList[i]).offset().top;
					if (sl > _l && st > _t && $(selList[i]).offset().left < _l + _w && $(selList[i]).offset().top < _t + _h) {
						$(selList[i]).addClass('seled')
					} else {
						$(selList[i]).removeClass('seled')
					}
				}
			}
			clearEventBubble(evt);
		}
		document.onmouseup = function () {
			isSelect = false;
			if (selDiv && selDiv.parentNode) {
				// document.body.removeChild(selDiv);
				selDiv.parentNode.removeChild(selDiv);
				showSelDiv(selList);
			}
		}
	}

	function clearEventBubble(evt) {
		if (evt.stopPropagation) {
			evt.stopPropagation();
		}
		else {
			evt.cancelBubble = true;
		}
		if (evt.preventDefault) {
			evt.preventDefault();
		} else {
			evt.returnValue = false;
		}
	}

	function showSelDiv(arr) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].className.indexOf("seled") != -1) {
				$("#" + arr[i].id).trigger("click");
			}
		}
	}
};